package com.airnewslinkosky.ticket.ui.flight;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.airnewslinkosky.ticket.FlyApplication;
import com.airnewslinkosky.ticket.R;
import com.airnewslinkosky.ticket.model.CabinItem;
import com.airnewslinkosky.ticket.model.Contactor;
import com.airnewslinkosky.ticket.model.DesUserOfficeSign;
import com.airnewslinkosky.ticket.model.FlightInfo;
import com.airnewslinkosky.ticket.model.FlightRestrict;
import com.airnewslinkosky.ticket.model.ItineraryInfo;
import com.airnewslinkosky.ticket.model.Passenger;
import com.airnewslinkosky.ticket.model.SearchFlight;
import com.airnewslinkosky.ticket.model.TotalOrderInfoResult;
import com.airnewslinkosky.ticket.net.WebAccessor;
import com.airnewslinkosky.ticket.net.type.RequestFlightOrder;
import com.airnewslinkosky.ticket.net.type.RequestInsuranceInfo;
import com.airnewslinkosky.ticket.net.type.RequestItineraryInfo;
import com.airnewslinkosky.ticket.net.type.RequestTotalOrder;
import com.airnewslinkosky.ticket.pay.util.BaseHelper;
import com.airnewslinkosky.ticket.sql.SqlUtils;
import com.airnewslinkosky.ticket.ui.BaseActivity;
import com.airnewslinkosky.ticket.util.AddrUtil;
import com.airnewslinkosky.ticket.util.Constants;
import com.airnewslinkosky.ticket.util.DateUtil;
import com.airnewslinkosky.ticket.util.FlyUtil;
import com.airnewslinkosky.ticket.util.StringUtil;
import com.airnewslinkosky.ticket.util.Utils;
import com.mobclick.android.MobclickAgent;

public class FlyOrderDetail extends BaseActivity implements
		AdapterView.OnItemClickListener {
	public static SearchFlight searchFlight;
	private Button backBut;
	
	public static FlightRestrict flightRestrict;
	public static FlightRestrict reFlightRestrict;
	
	private RelativeLayout flightDetailRestrict;
	private TextView restrict;
	private ImageView restrictArrow;
	private String restrictValue;
	//返程退改签政策
	private RelativeLayout t_flightDetailRestrict;
	private TextView t_restrict;
	private ImageView t_restrictArrow;
	private String t_restrictValue;
	
	public final int CITY_LIST = 1;
	public final int FLYCOM_LIST = 2;
	public final int NORESULT = 3;
	public final int NOORDER = 4;
	public final int NOORDERSTAT = 5;
	public final int NET_ERROR=6;
	public final int SEARCH_ERROR=7;
	public  final int TIME_DIALOG_ID = 8;
	public  final int DIALOG_SINGLE_CHOICE = 9;
	public  final int DIALOG_LIST = 10;
	public  final int DATE_DIALOG_ID = 11;
	public final int SUCCESS=12;
	public final int ORDER_ERROR = 13;
	
//	public static List<Flight1> flist;
	public static FlightInfo flight;
	public static FlightInfo returnFlight;
	public static String isItinerary;//是否需要行程单
	public static String isInsurance = "0";//是否需要保险
	
	public static List<Map<String,String>> passengerList = new ArrayList<Map<String,String>>();
	public static List<Map<String,String>> contactList = new ArrayList<Map<String,String>>();
	public static List<Map<String,String>> itineraryList = new ArrayList<Map<String,String>>();
	public static List<Map<String,String>> mileagerInfoList = new ArrayList<Map<String,String>>();
	public static ItineraryInfo itineraryInfo = new ItineraryInfo();
	
	private FlyUtil flyUtil;
	private RelativeLayout mBtnNext;
	List<Map<String, String>> data = new ArrayList<Map<String, String>>();

	private ProgressDialog progressDialog = null;
	public Handler myHandler;
	
	private TextView button_next,button_pay;
	
	private Button needItineraryBut;
	
	private String baseCabinV = "";
	private String sumPriceFormat = "";
	
	public SimpleAdapter passenger_sa,contactor_sa,itinerary_sa,mileager_sa;
	public ListView lv_passenger,lv_contactor,lv_itinerary,lv_mileager;
	
	List<Map<String, Object>> pdata = new ArrayList<Map<String, Object>>();
	private float sumDoublePrice = 0;
	
	private SharedPreferences sp;
	private Toast toast;
	
	private boolean isNowPay = true;//是否马上支付
	
	//保险、行程单价格
	private TextView insurance_shuomin,itinerary_price;
	private float insuranceShuominPrice,itineraryPrice;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.fly_order_detail);
		// 删除窗口背景
        getWindow().setBackgroundDrawable(null);
        
		activityList.add(this);
		
		flyUtil = new FlyUtil(this);
		
		renderPassData();
		renderContactData();
		
		AddrUtil addrUtil = new AddrUtil(this);
		
		insurance_shuomin = (TextView) findViewById(R.id.insurance_shuomin);
		itinerary_price = (TextView) findViewById(R.id.itinerary_price);
		
		TextView departureDate = (TextView) findViewById(R.id.departureDate);
		String departureTime=flight.departureTime;
		if(departureTime!=null&&departureTime.length()>=10){
			departureTime = departureTime.substring(0,10);
		}
		departureDate.setText("去程 " + departureTime);
		TextView departureWeek = (TextView) findViewById(R.id.departureWeek);
		departureWeek.setText(DateUtil.getWeek("yyyy-MM-dd", departureTime));
		
		TextView fromCity = (TextView) findViewById(R.id.fromCity);
		fromCity.setText(addrUtil.getCityByCode(flight.departure).getCity());
		TextView toCity = (TextView) findViewById(R.id.toCity);
		toCity.setText(addrUtil.getCityByCode(flight.arrival).getCity());
		
		TextView fromtime = (TextView) findViewById(R.id.fromtime);
		fromtime.setText(StringUtil.getTime(flight.departureTime));
		TextView totime = (TextView) findViewById(R.id.totime);
		totime.setText(StringUtil.getTime(flight.arrivalTime));
		TextView fromaf = (TextView) findViewById(R.id.fromaf);
		fromaf.setText(addrUtil.getCityByCode(flight.departure)
				.getAirName());
		TextView toaf = (TextView) findViewById(R.id.toaf);
		toaf.setText(addrUtil.getCityByCode(flight.arrival).getAirName());
		TextView flightno = (TextView) findViewById(R.id.flightNo);
		flightno.setText( flyUtil.getName(flight.airline)+ " " + flight.flightNo);
		TextView airc = (TextView) findViewById(R.id.airc);
		airc.setText(flight.planeType);
		
		TextView stopNo = (TextView) findViewById(R.id.stopNo);
		String stopNoValue = flight.stopNo == 0 ? "有" : "无";
		stopNo.setText(stopNoValue);
		
		String food = flight.isFood == 0 ? "有" : "无";
		TextView foodText = (TextView) findViewById(R.id.food);
		foodText.setText(food);
		
		TextView cabinPrice = (TextView) findViewById(R.id.cabinPrice);
		TextView price = (TextView) findViewById(R.id.price);
		TextView fuelTax = (TextView) findViewById(R.id.fuelTax);
		TextView baseCabin = (TextView) findViewById(R.id.baseCabin);
		TextView basePrice = (TextView) findViewById(R.id.basePrice);
		TextView discount = (TextView) findViewById(R.id.discount);
		
		List<CabinItem> cabinlist = flight.cabinItems;
		if(cabinlist!=null&&cabinlist.size()>0){
        	CabinItem cabinItem= cabinlist.get(0);//cabinlist.size()-1
        	if(flight.cabinItemDetail!=null){
        		System.out.println("子列数据");
        		cabinItem = flight.cabinItemDetail;
        	}

			baseCabin.setText(FlyUtil.getJClassName(cabinItem.baseCabin) + " " + cabinItem.baseCabin);
			
			String priceFormat = cabinItem.price.indexOf(".00") != -1 ? cabinItem.price.substring(0, cabinItem.price.indexOf(".00")) : cabinItem.price;
        	String ibePaymentFormat = cabinItem.ibePayment.indexOf(".00") != -1 ? cabinItem.ibePayment.substring(0, cabinItem.ibePayment.indexOf(".00")) : cabinItem.ibePayment;
        	String cabinPriceFormat = cabinItem.cabinPrice.indexOf(".00") != -1 ? cabinItem.cabinPrice.substring(0, cabinItem.cabinPrice.indexOf(".00")) : cabinItem.cabinPrice;
        	Float priceCal = Float.parseFloat(cabinPriceFormat) - Float.parseFloat(ibePaymentFormat);
        	
			cabinPrice.setText("票价:" +cabinPriceFormat + "元");
			price.setText("  净价:" + String.valueOf(priceCal)  + "元");
			discount.setText("("+FlyUtil.parseDiscount(cabinItem.discount)+")");
//			discount.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG );
			basePrice.setText("             返点：" + ibePaymentFormat + "元");
			
//			cabinPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG );
			((TextView) findViewById(R.id.flight_ticket_type)).setText(cabinItem.ticketType);
			
//			cabinPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG );
			String airportTaxV = (cabinItem.airportTax.equals("") ||  (cabinItem.airportTax == null) ? "0" : cabinItem.airportTax) ;
			String fuelTaxV = (cabinItem.fuelTax.equals("") || (cabinItem.fuelTax == null) ? "0" : cabinItem.fuelTax);
			fuelTax.setText("￥" + airportTaxV + "/￥" + fuelTaxV );
			
			float sumPrice = Float.valueOf(priceCal) + Float.valueOf(airportTaxV) + Float.valueOf(fuelTaxV);
			
			sumDoublePrice = sumDoublePrice + sumPrice;
			sumDoublePrice = sumDoublePrice * passengerList.size();
			
			if(isInsurance.equals("0")){
				insuranceShuominPrice = 20.0f * passengerList.size();
			} else {
				insuranceShuominPrice = 0;
			}
			insurance_shuomin.setText("￥" + insuranceShuominPrice + "元");
		}
		
		if(returnFlight!=null){
			LinearLayout returnFlyLayout =  (LinearLayout) findViewById(R.id.returnFlyLayout);
			returnFlyLayout.setVisibility(View.VISIBLE);
			
			TextView t_departureDate = (TextView) findViewById(R.id.t_departureDate);
			String t_departureTime=returnFlight.departureTime;
			if(t_departureTime!=null&&t_departureTime.length()>=10){
				t_departureTime = t_departureTime.substring(0,10);
			}
			t_departureDate.setText("回程 " + t_departureTime);
			TextView t_departureWeek = (TextView) findViewById(R.id.t_departureWeek);
			t_departureWeek.setText(DateUtil.getWeek("yyyy-MM-dd", t_departureTime));
			
			TextView t_fromCity = (TextView) findViewById(R.id.t_fromCity);
			t_fromCity.setText(addrUtil.getCityByCode(returnFlight.departure).getCity());
			TextView t_toCity = (TextView) findViewById(R.id.t_toCity);
			t_toCity.setText(addrUtil.getCityByCode(returnFlight.arrival).getCity());
			
			TextView t_fromtime = (TextView) findViewById(R.id.t_fromtime);
			t_fromtime.setText(StringUtil.getTime(returnFlight.departureTime));
			TextView t_totime = (TextView) findViewById(R.id.t_totime);
			t_totime.setText(StringUtil.getTime(returnFlight.arrivalTime));
			TextView t_fromaf = (TextView) findViewById(R.id.t_fromaf);
			t_fromaf.setText(addrUtil.getCityByCode(returnFlight.departure)
					.getAirName());
			TextView t_toaf = (TextView) findViewById(R.id.t_toaf);
			t_toaf.setText(addrUtil.getCityByCode(returnFlight.arrival).getAirName());
			TextView t_flightno = (TextView) findViewById(R.id.t_flightNo);
			t_flightno.setText( flyUtil.getName(returnFlight.airline)+ " " + returnFlight.flightNo);
			TextView t_airc = (TextView) findViewById(R.id.t_airc);
			t_airc.setText(returnFlight.planeType);
			
			TextView t_stopNo = (TextView) findViewById(R.id.t_stopNo);
			String t_stopNoValue = returnFlight.stopNo == 0 ? "有" : "无";
			t_stopNo.setText(t_stopNoValue);
			
			String t_food = returnFlight.isFood == 0 ? "有" : "无";
			TextView t_foodText = (TextView) findViewById(R.id.t_food);
			t_foodText.setText(t_food);
			
			TextView t_cabinPrice = (TextView) findViewById(R.id.t_cabinPrice);
			TextView t_price = (TextView) findViewById(R.id.t_price);
			TextView t_fuelTax = (TextView) findViewById(R.id.t_fuelTax);
			TextView t_baseCabin = (TextView) findViewById(R.id.t_baseCabin);
			TextView t_basePrice = (TextView) findViewById(R.id.t_basePrice);
			TextView t_discount = (TextView) findViewById(R.id.t_discount);
			
//			TextView t_airc0 = (TextView) findViewById(R.id.t_airc0);//更改条件
//			TextView t_others = (TextView) findViewById(R.id.t_others);//退票条件
//			TextView t_airc1 = (TextView) findViewById(R.id.t_airc1);//签转条件
//			TextView t_airc2 = (TextView) findViewById(R.id.t_airc2);//备　　注
			
			List<CabinItem> t_cabinlist = returnFlight.cabinItems;
			if(t_cabinlist!=null&&t_cabinlist.size()>0){
	        	CabinItem cabinItem= t_cabinlist.get(0);//cabinlist.size()-1
	        	t_baseCabin.setText(FlyUtil.getJClassName(cabinItem.baseCabin) + " " + cabinItem.baseCabin);
				
	        	String priceFormat = cabinItem.price.indexOf(".00") != -1 ? cabinItem.price.substring(0, cabinItem.price.indexOf(".00")) : cabinItem.price;
	        	String ibePaymentFormat = cabinItem.ibePayment.indexOf(".00") != -1 ? cabinItem.ibePayment.substring(0, cabinItem.ibePayment.indexOf(".00")) : cabinItem.ibePayment;
	        	String cabinPriceFormat = cabinItem.cabinPrice.indexOf(".00") != -1 ? cabinItem.cabinPrice.substring(0, cabinItem.cabinPrice.indexOf(".00")) : cabinItem.cabinPrice;
	        	Float priceCal = Float.parseFloat(cabinPriceFormat) - Float.parseFloat(priceFormat);
	        	
	        	t_cabinPrice.setText("￥" +cabinPriceFormat + "元");
	        	t_price.setText("￥" + String.valueOf(priceFormat)  + "元");
	        	t_discount.setText("(" + FlyUtil.parseDiscount(cabinItem.discount)  + ")");
	        	t_discount.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG );
	        	t_basePrice.setText("          返还" + priceCal + "元");
	        	
				t_cabinPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG );
				String airportTaxV = (cabinItem.airportTax.equals("") ||  (cabinItem.airportTax == null) ? "0" : cabinItem.airportTax) ;
				String fuelTaxV = (cabinItem.fuelTax.equals("") || (cabinItem.fuelTax == null) ? "0" : cabinItem.fuelTax);
				t_fuelTax.setText("￥" + airportTaxV + "/￥" + fuelTaxV );
				
				float sumPrice = Float.valueOf(cabinItem.price) + Float.valueOf(airportTaxV) + Float.valueOf(fuelTaxV);
				
				sumDoublePrice =  sumDoublePrice + sumPrice;
				sumDoublePrice = sumDoublePrice * passengerList.size();
//				t_others.setText(returnFlightRestrict.airc0);
				
				if(isInsurance.equals("0")){
					insuranceShuominPrice = 40.0f * passengerList.size();
				} else {
					insuranceShuominPrice = 0;
				}
				insurance_shuomin.setText("￥" + insuranceShuominPrice + "元");
			}
		}
		
	    if("2".equals(isItinerary)){
	    	LinearLayout itineraryLayout = (LinearLayout) findViewById(R.id.flight_itinerary);
	    	itineraryLayout.setVisibility(View.VISIBLE);
	    	renderItineraryData();
	    	itineraryPrice = 5.0f;
	    } else {
	    	itineraryPrice = 0.0f;
	    }
	    itinerary_price.setText("￥" + itineraryPrice + "元");
	    
	    if(mileagerInfoList!=null && mileagerInfoList.size()>0){
	    	LinearLayout flight_mileager = (LinearLayout) findViewById(R.id.flight_mileager);
	    	flight_mileager.setVisibility(View.VISIBLE);
	    	renderMileagerData();
	    }
	    
	    TextView sumPriceText = (TextView) findViewById(R.id.sumPrice);
	    sumDoublePrice = sumDoublePrice + insuranceShuominPrice + itineraryPrice;
       	sumPriceFormat = String.valueOf(sumDoublePrice).indexOf(".0") != -1 ? String.valueOf(sumDoublePrice).substring(0, String.valueOf(sumDoublePrice).indexOf(".0")) : String.valueOf(sumDoublePrice);
		sumPriceText.setText(" 总支付：" + sumPriceFormat + "元");
		
	    backBut = (Button)findViewById(R.id.backBut);
		
		OnClickListener b_ocl= new OnClickListener() { 
	    	public void onClick(View v) { 
	    		switch (v.getId()) {
	    		case R.id.backBut:
	    			Intent intent3 = new Intent();
	    			intent3.setClass(FlyOrderDetail.this, FlyOrderInput.class);
	    			FlyOrderInput.flight = flight;
	    			FlyOrderInput.returnFlight = returnFlight;
	    			FlyOrderInput.passengerList = passengerList;
	    			FlyOrderInput.contactList = contactList;
	    			FlyOrderInput.isItinerary = isItinerary;
	    			FlyOrderInput.isInsurance = isInsurance;
	    			FlyOrderInput.itineraryInfo = itineraryInfo;
	    			FlyOrderInput.searchFlight = searchFlight;
	    			startActivity(intent3);
	    			break;
	    		case R.id.button_next:
	    			isNowPay = false;
	    			commitOrder(isNowPay);
	    			break;
	    		case R.id.sumPrice:
	    			commitOrder(isNowPay);
	    			break;
	    		case R.id.button_pay:
	    			isNowPay = true;
	    			commitOrder(isNowPay);
	    			break;
	    		case R.id.flight_detail_restrict:
	    			String detailRestrict = ((FlyApplication)getApplication()).getPolicyRule();
	    			if(detailRestrict == null){
	    				getFlightRestrict();
	    			}
	    			break;
	    		case R.id.t_flight_detail_restrict:
	    			String t_detailRestrict = ((FlyApplication)getApplication()).getRePolicyRule();
	    			if(t_detailRestrict == null){
	    				getReturnFlightRestrict();
	    			}
	    			break;
	    		}
	    	}
		};
		
		button_next = (TextView)findViewById(R.id.button_next);
		button_pay = (TextView)findViewById(R.id.button_pay);
		button_next.setOnClickListener(b_ocl);
		button_pay.setOnClickListener(b_ocl);
		
		//退改签
		flightDetailRestrict = (RelativeLayout) findViewById(R.id.flight_detail_restrict);
		flightDetailRestrict.setOnClickListener(b_ocl);
		restrict = (TextView) findViewById(R.id.restrict);
		restrictArrow = (ImageView) findViewById(R.id.restrictArrow);
		
		String detailRestrict = ((FlyApplication)getApplication()).getPolicyRule();
		System.out.println("create detailRestrict = " + detailRestrict);
		if(detailRestrict != null){
			restrict.setText(detailRestrict);
			restrictArrow.setVisibility(View.GONE);
		}
		
		//退改签
		t_flightDetailRestrict = (RelativeLayout) findViewById(R.id.t_flight_detail_restrict);
		t_flightDetailRestrict.setOnClickListener(b_ocl);
		t_restrict = (TextView) findViewById(R.id.t_restrict);
		t_restrictArrow = (ImageView) findViewById(R.id.t_restrictArrow);
		
//		String detailReRestrict = ((FlyApplication)getApplication()).getRePolicyRule();
//		System.out.println("create detailReRestrict = " + detailReRestrict);
//		if(detailReRestrict != null){
//			t_restrict.setText(detailReRestrict);
//			t_restrictArrow.setVisibility(View.GONE);
//		}
		
		backBut.setOnClickListener(b_ocl);
	    //new GetWeatherIcon().execute(eDeparture,eArrival);
		myHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case NORESULT:
					toast = Toast.makeText(FlyOrderDetail.this, "未找到符合条件的航班", Toast.LENGTH_LONG);
					toast.setGravity(Gravity.CENTER, 0, 0);
					toast.show();
					break;
				case NOORDER:
					toast = Toast.makeText(FlyOrderDetail.this, "无订单信息", Toast.LENGTH_LONG);
					toast.setGravity(Gravity.CENTER, 0, 0);
					toast.show();
					break;
				case NOORDERSTAT:
					toast = Toast.makeText(FlyOrderDetail.this, "订单信息未获得更新", Toast.LENGTH_LONG);
					toast.setGravity(Gravity.CENTER, 0, 0);
					toast.show();
					break;
				case NET_ERROR:
					toast = Toast.makeText(FlyOrderDetail.this, "网络超时，连接失败", Toast.LENGTH_LONG);
					toast.setGravity(Gravity.CENTER, 0, 0);
					toast.show();
					break;
				case SEARCH_ERROR:
					BaseHelper.showDialog(
							FlyOrderDetail.this,
							"提交失败",
							(String)msg.obj,
							android.R.drawable.ic_dialog_alert);
					break;
				case ORDER_ERROR:
					BaseHelper.showDialog(
							FlyOrderDetail.this,
							"提交失败",
							"由于网络原因，未能生成订单号，请稍候再试。",
							android.R.drawable.ic_dialog_alert);
					break;
				}
				super.handleMessage(msg);
			}
		};
	}
	
	private void renderPassData(){
		//登机人
		passenger_sa = new SimpleAdapter(
				this,
				passengerList,
				R.layout.flight_passenger_item,
				new String[] { "passengerName", "passengerIdNumber"},
				new int[] { R.id.passenger_name, R.id.passenger_id_number});
		lv_passenger = (ListView) findViewById(R.id.passenger_list);
		lv_passenger.setDivider(null);
		lv_passenger.setAdapter(passenger_sa);
		Utils.setListViewHeightBasedOnChildren(lv_passenger);//更新list高度
	}
	
	private void renderContactData() {
		//联系人
		contactor_sa = new SimpleAdapter(
				this,
				contactList,
				R.layout.flight_contactor_item,
				new String[] { "contactName", "phone"},
				new int[] { R.id.contactor_name, R.id.contactor_mobile});
		lv_contactor = (ListView) findViewById(R.id.contactor_list);
		lv_contactor.setDivider(null);
		lv_contactor.setAdapter(contactor_sa);
		Utils.setListViewHeightBasedOnChildren(lv_contactor);
	}

	private void renderItineraryData(){
		//收件人
		itinerary_sa = new SimpleAdapter(
				this,
				itineraryList,
				R.layout.flight_itinerary_item,
				new String[] { "consigneeName", "consigneePhone","consigneeAddress"},
				new int[] { R.id.consigneeName, R.id.consigneePhone, R.id.consigneeAddress});
		lv_itinerary = (ListView) findViewById(R.id.itinerary_list);
		lv_itinerary.setDivider(null);
		lv_itinerary.setAdapter(itinerary_sa);
	}

	private void renderMileagerData(){
		//收件人
		mileager_sa = new SimpleAdapter(
				this,
				mileagerInfoList,
				R.layout.flight_mileager_item,
				new String[] { "mileagerCardAirline", "mileagerCardNumber"},
				new int[] { R.id.mileagerCardAirline, R.id.mileagerCardNumber});
		lv_mileager = (ListView) findViewById(R.id.mileager_list);
		lv_mileager.setDivider(null);
		lv_mileager.setAdapter(mileager_sa);
	}
	
	private void commitOrder(final boolean isPay) {
		progressDialog = ProgressDialog.show(this, "请稍等...", "提交机票订单可能会\n占用比较长时间...",true);
		final Thread thread = new Thread() {
			public void run() {
		        try {
//		        	sp = getSharedPreferences("UserInfoB2B", Context.MODE_WORLD_WRITEABLE | Context.MODE_WORLD_READABLE);
//			        String userIdLogin = sp.getString("userIdB2B", null);
//			        String userPwd =  sp.getString("userPwdB2B", null);
			        
			        String userIdLogin = Constants.USERID;
			        String userPwd =  Constants.USERPWD;
			        String asToken =  Constants.ASToken;
			        
			        DesUserOfficeSign ds = WebAccessor.buildDesUserOfficeSign(userIdLogin,userPwd);
					//生成订单号
		            String orderno = WebAccessor.GenerateOrderNO(userIdLogin,userPwd,ds);
		            if(orderno==null){
		            	Message msg = new Message();
						msg.what = ORDER_ERROR;
						myHandler.sendMessage(msg);
		            }
		            Contactor contactor = null;
		            for (int i = 0; i < contactList.size(); i++) {
		    			Map<String,String> m = contactList.get(i);
		    			contactor = new Contactor();
		    			contactor.setEmail(m.get("email"));
		    			contactor.setContactName(m.get("contactName"));
		    			contactor.setPhone(m.get("phone"));
		            }
		            String xml = createTotalOrderXml(orderno,contactor,ds);
		            //System.out.println(new String(xml.getBytes(),"UTF8"));
		            System.out.println(xml);
		            TotalOrderInfoResult orderResult = WebAccessor.TotalOrderRequest(xml);
		            System.out.println(orderResult);
					if (progressDialog.isShowing()) {
						if (orderResult== null) {
							Message msg = new Message();
							msg.what = NORESULT;
							myHandler.sendMessage(msg);
						}else if(!"0".equals(orderResult.Ret_Code)){
							Message msg = new Message();
							msg.what = SEARCH_ERROR;
							msg.obj = orderResult.Ret_Msg;
							myHandler.sendMessage(msg);
						}else{
								if(isNowPay){
									Intent intent = new Intent();
					    			intent.setClass(FlyOrderDetail.this, CreditCard.class);
					    			CreditCard.totalOrderInfoResult = orderResult;
					    			CreditCard.sumPriceFormat = sumPriceFormat;
					    			CreditCard.flight = flight;
					    			CreditCard.returnFlight = returnFlight;
					    			CreditCard.passengerList = passengerList;
					    			CreditCard.contactList = contactList;
					    			CreditCard.isItinerary = isItinerary;
					    			CreditCard.isInsurance = isInsurance;
					    			CreditCard.itineraryList = itineraryList;
					    			CreditCard.searchFlight = searchFlight;
					    			CreditCard.isNowPay = isPay;
					    			startActivity(intent);
								} else {
									Intent intentS = new Intent();
									intentS.setClass(FlyOrderDetail.this, FlyOrderSave.class);
									FlyOrderSave.flight = flight;
									FlyOrderSave.passengerList = passengerList;
									FlyOrderSave.contactList = contactList;
					    			FlyOrderSave.itineraryList = itineraryList;
					    			FlyOrderSave.isItinerary = isItinerary;
					    			FlyOrderSave.isInsurance = isInsurance;
					    			FlyOrderSave.OrderNo = orderResult.OrderNO;
					    			FlyOrderSave.FlightOrderNO = orderResult.FlightOrderNO;
									startActivity(intentS);
								}
								
						}
						progressDialog.dismiss();
					}
		        } catch (Exception e) {
					//Toast.makeText(FlyOrderDetail.this, "错误信息:" + e.getMessage(), Toast.LENGTH_LONG).show();
					e.printStackTrace();
				}
			}
		};
		progressDialog.setCancelable(true);
		thread.start();
	}
	
	//保存登机人入数据库中
	private void saveToDbOfPassengerData() {
		for (int i = 0; i < passengerList.size(); i++) {
			Map<String,String> m = passengerList.get(i);
			Passenger passengerNew = new Passenger();
			passengerNew.setPassengerName(m.get("passengerName"));
			passengerNew.setPassengerIDType(m.get("passengerIDType"));
			passengerNew.setPassengerIDNo(m.get("passengerIDNo"));
			passengerNew.setPassagerBirthday(m.get("passagerBirthday"));
			passengerNew.setPassengerMobile (m.get("passengerMobile"));
			SqlUtils.setPassenger(FlyOrderDetail.this, passengerNew);
		}
	}
	
	private String createTotalOrderXml(String orderno,Contactor contactor,DesUserOfficeSign ds) {
		StringBuffer sb = new StringBuffer("");
		RequestTotalOrder orderinfo = new RequestTotalOrder();
		orderinfo.setAsID(Constants.ASID + Constants.OfficeID);
		orderinfo.setAsPriority("0");
		orderinfo.setTimeStamp(DateUtil.getDateTime());
		orderinfo.setUserSign(ds.getUserSign());
		orderinfo.setOfficeSign(ds.getOfficeSign());
		orderinfo.setOperateType("A");
		orderinfo.setMethod("TotalOrder");
		orderinfo.setTrade_Info(flight.flightId);
		orderinfo.setOrderNO(orderno);
//		orderinfo.setOrderTicketName(contactor.getContactName());
//		orderinfo.setOrderTicketPhone(contactor.getPhone());
        sb.append(orderinfo.getRequestData().replaceAll("</asoc:OrderInfoV1>", ""));
        sb.append("<asoc:TicketOrdersV1>");
        for (int i = 0; i < passengerList.size(); i++) {
			Map<String,String> m = passengerList.get(i);
			Passenger passengerNew = new Passenger();
			passengerNew.setPassengerName(m.get("passengerName"));
			passengerNew.setPassengerIDType(m.get("passengerIDType"));
			passengerNew.setPassengerIDNo(m.get("passengerIDNo"));
			passengerNew.setPassagerBirthday(m.get("passagerBirthday"));
			sb.append(createFlightOrderXml(orderno, passengerNew, contactor));

		}
        sb.append("</asoc:TicketOrdersV1>");
        sb.append("</asoc:OrderInfoV1>");
        sb.append("</asoc:TotalOrder>");
        sb.append("</soapenv:Body>");
        sb.append("</soapenv:Envelope>");
		return  sb.toString();
	}
	
	private String createFlightOrderXml(String orderno,Passenger passenger,Contactor contactor) {
		StringBuffer sb = new StringBuffer("");
		RequestFlightOrder flightorderdetail = new RequestFlightOrder();
        flightorderdetail.setCabin(baseCabinV);
        flightorderdetail.setFlightId(flight.flightId);
        flightorderdetail.setIbEPolicyID("719259");
        flightorderdetail.setTicketType("0");
        
        List<CabinItem> cabinlist = flight.cabinItems;
		if(cabinlist!=null&&cabinlist.size()>0){
			CabinItem cabinItem= cabinlist.get(0);
			flightorderdetail.setCabinPrice(cabinItem.cabinPrice);
			flightorderdetail.setPrice(cabinItem.price);
			flightorderdetail.setCabin((cabinItem.baseCabin+flightorderdetail.getTicketType()));
		}
        
		flightorderdetail.setPassengerName(passenger.getPassengerName());
        flightorderdetail.setPassengerIDType(passenger.getPassengerIDType());
        flightorderdetail.setPassengerIDNO(passenger.getPassengerIDNo());
        flightorderdetail.setPassagerType(passenger.getPassagerType());
        flightorderdetail.setPassagerBirthday(passenger.getPassagerBirthday());
        if(mileagerInfoList.size() != 0){
    		Map<String, String> m = mileagerInfoList.get(0);
    		flightorderdetail.setMileageCardAirline(FlyUtil.getAirlineKey(m.get("mileagerCardAirline")));
    		flightorderdetail.setMileageCardNO(m.get("mileagerCardNumber"));
    	}
        flightorderdetail.setContactEmail(contactor.getEmail());
        flightorderdetail.setContactName(contactor.getContactName());
        flightorderdetail.setContactPhone(contactor.getPhone());
        flightorderdetail.setIsItinerary(isItinerary);
        flightorderdetail.setFlightAmountPrice(String.valueOf(sumDoublePrice));
        
        sb.append(flightorderdetail.getRequestData().replaceAll("</asoc:TicketOrderV1>", ""));
        if(isItinerary.equals("2")){
        	sb.append(createItineraryOrderInfoXml(orderno,passenger));
        }
        if(isInsurance.equals("0")){
        	sb.append(createInsuranceInfoXml());
        }
        sb.append("</asoc:TicketOrderV1>");
        return sb.toString();
	}
	
	
	private String createItineraryOrderInfoXml(String orderno,Passenger passenger) {
		RequestItineraryInfo itineraryinfo = new RequestItineraryInfo();
		
		if(itineraryList.size() != 0){
			Map<String, String> m = itineraryList.get(0);
			itineraryinfo.setConsigneeName(m.get("consigneeName"));
			itineraryinfo.setConsigneePhone(m.get("consigneePhone"));
			itineraryinfo.setConsigneeAddress(m.get("consigneeAddress"));
			itineraryinfo.setConsigneeZIP(m.get("consigneeZIP"));
			itineraryinfo.setPostCost(String.valueOf(itineraryPrice));
			itineraryinfo.setInvoiceFee("0");
//	        itineraryinfo.setPassengerName(passenger.getPassengerName());
//	        itineraryinfo.setPassengerIDType(passenger.getPassengerIDType());
//	        itineraryinfo.setPassengerIDNO(passenger.getPassengerIDNo());
		}
		
		return itineraryinfo.getRequestData();
	}

	private String createInsuranceInfoXml() {
		RequestInsuranceInfo insuranceInfo = new RequestInsuranceInfo();
		String iPrice = "";
		String sumIprice = "";
		if(returnFlight!=null){
			if(passengerList.size() != 0){
				iPrice = "40";
				sumIprice = String.valueOf(passengerList.size()*40);
			}
		} else {
			if(passengerList.size() != 0){
				iPrice = "20";
				sumIprice = String.valueOf(passengerList.size()*20);
			}
		}
		if(passengerList.size() != 0){
			insuranceInfo.setInsurancePrice(iPrice);
			insuranceInfo.setCopies(String.valueOf(passengerList.size()));
			insuranceInfo.setInsuranceAmount(sumIprice);
		}
		return insuranceInfo.getRequestData();
	}
	
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// TODO Auto-generated method stub
		
	}
	
	private void getFlightRestrict() {
		progressDialog = ProgressDialog.show(this, "请稍等...", "查询退改签明细...",true);
		final Thread thread = new Thread() {
			public void run() {
				flightRestrict =  WebAccessor.getFlightRestrict(FlyOrderDetail.this,flight);
				
				if (progressDialog.isShowing()) {
					if (flightRestrict!= null) {
						Message msg = new Message();
						msg.what = SUCCESS;
						restrictHandler.sendMessage(msg);
					} else {
						Message msg = new Message();
						msg.what = SEARCH_ERROR;
						msg.obj = "无法查询到退改签明细";
						restrictHandler.sendMessage(msg);
					}
					progressDialog.dismiss();
				}
			}
		};
		progressDialog.setCancelable(true);
		thread.start();
	}
	
	public Handler restrictHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case SEARCH_ERROR:
				Toast.makeText(FlyOrderDetail.this, (String)msg.obj, Toast.LENGTH_LONG).show();
				break;
			case SUCCESS:
				restrictValue = flightRestrict.airc0;
				//退订票规则
				((FlyApplication)getApplication()).setPolicyRule(restrictValue);
				System.out.println("restrictValue="+restrictValue);
				restrict.setText(restrictValue);
				restrictArrow.setVisibility(View.GONE);
				break;
			}
		}
	};
	
	
	private void getReturnFlightRestrict() {
		progressDialog = ProgressDialog.show(this, "请稍等...", "查询退改签明细...",true);
		final Thread thread = new Thread() {
			public void run() {
				reFlightRestrict =  WebAccessor.getFlightRestrict(FlyOrderDetail.this,returnFlight);
				
				if (progressDialog.isShowing()) {
					if (reFlightRestrict!= null) {
						Message msg = new Message();
						msg.what = SUCCESS;
						t_restrictHandler.sendMessage(msg);
					} else {
						Message msg = new Message();
						msg.what = SEARCH_ERROR;
						msg.obj = "无法查询到退改签明细";
						t_restrictHandler.sendMessage(msg);
					}
					progressDialog.dismiss();
				}
			}
		};
		progressDialog.setCancelable(true);
		thread.start();
	}
	
	public Handler t_restrictHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case SEARCH_ERROR:
				Toast.makeText(FlyOrderDetail.this, (String)msg.obj, Toast.LENGTH_LONG).show();
				break;
			case SUCCESS:
				t_restrictValue = reFlightRestrict.airc0;
				//退订票规则
				((FlyApplication)getApplication()).setRePolicyRule(t_restrictValue);
				System.out.println("t_restrictValue="+t_restrictValue);
				t_restrict.setText(t_restrictValue);
				t_restrictArrow.setVisibility(View.GONE);
				break;
			}
		}
	};
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if(keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0){
			Intent intent3 = new Intent();
			intent3.setClass(FlyOrderDetail.this, FlyOrderInput.class);
			FlyOrderInput.flight = flight;
			FlyOrderInput.searchFlight = searchFlight;
			FlyOrderInput.returnFlight = null;
			startActivity(intent3);
			return true;
		}
		return super.onKeyDown(keyCode, event);
	} 
	
	public void onResume() {     
		super.onResume();     
		MobclickAgent.onResume(this); 
	}  
	
	public void onPause() {     
		super.onPause();     
		MobclickAgent.onPause(this); 
	}  
}
